def vertex2bin(vertex):
	bin = ""
	for x in vertex:
		bin += str(int(x))
	return bin

def readContext(dbfile):
	
	print "Reading context..."
	matrix = []
	matrixfile = open(dbfile,"r")
	l=0
	lcounter = 0
	intent = []
	extent = []
	fs0 = []
	for line in matrixfile:
		lcounter += 1
		if lcounter == 5:
			extent = line.replace("\n","").split(" | ")
			if "" in extent:
				extent.remove("")
		elif lcounter == 6:
			intent = line.replace("\n","").split(" | ")
			if "" in intent:
				intent.remove("")
		elif ((lcounter >= 7) & (line.replace("\n","") != "[END Relational Context]")):
			values = line.replace("\n","").split(" ")
			row=[]
			#print values
			for i in values:
				if i != "":
					row.append(float(i))
					if float(i) > 0:
						fs0.append(float(i))
			matrix.append(row)
	return matrix,extent,intent

def writeContext(filename,matrix,extent,intent,path="",context_name="Default Name", dataset_name="Name_of_dataset",bin=False):
	print "Writing context..."
	salida = "[Relational Context]\n"+context_name+"\n[Binary Relation]\n"+dataset_name+"("+ str(len(extent)) +"x"+ str(len(intent)) + ")\n"
	for i in extent:
		salida += str(i) + " | "
	salida += "\n"
	for e in intent:
		salida += str(e) + " | "
	salida += "\n"
	for i in matrix:
		for k in i:
			if bin:
				if k > 0:
					salida += "1 "
				else:
					salida += "0 "
			else:
				salida += str(k) + " "
		salida += "\n"
	salida += "[END Relational Context]"
	filepath =path+filename 
	f1 = open(filepath,"w")
	f1.write(salida)
	f1.close()
	return filepath

